package com.example.teaching_server.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 教学分类实体类
 *
 * @author Teaching Server
 * @since 1.0.0
 */
@Getter
@Setter
@ToString(exclude = "subcategories")
@EqualsAndHashCode(of = "id")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "teaching_categories", indexes = {
        @Index(name = "idx_category_grade", columnList = "grade_id"),
        @Index(name = "idx_category_sort", columnList = "sortOrder")
})
public class TeachingCategory {

    /**
     * 分类ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 年级ID
     */
    @NotNull(message = "年级ID不能为空")
    @Column(name = "grade_id", nullable = false)
    private Integer gradeId;

    /**
     * 分类名称
     */
    @NotBlank(message = "分类名称不能为空")
    @Size(max = 100, message = "分类名称长度不能超过100个字符")
    @Column(nullable = false, length = 100)
    private String name;

    /**
     * 图标
     */
    @Size(max = 100, message = "图标路径长度不能超过100个字符")
    @Column(length = 100)
    private String icon;

    /**
     * 排序顺序
     */
    @Builder.Default
    @Column(name = "sort_order")
    private Integer sortOrder = 0;

    /**
     * 创建时间
     */
    @CreationTimestamp
    @Column(name = "created_at", updatable = false)
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @UpdateTimestamp
    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    /**
     * 子分类列表
     */
    @Builder.Default
    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @OrderBy("sortOrder ASC")
    private List<TeachingSubcategory> subcategories = new ArrayList<>();

    /**
     * 添加子分类
     */
    public void addSubcategory(TeachingSubcategory subcategory) {
        subcategories.add(subcategory);
        subcategory.setCategory(this);
    }

    /**
     * 移除子分类
     */
    public void removeSubcategory(TeachingSubcategory subcategory) {
        subcategories.remove(subcategory);
        subcategory.setCategory(null);
    }

    /**
     * 验证分类是否有效
     */
    public boolean isValid() {
        return name != null && !name.trim().isEmpty() && gradeId != null;
    }
}
